﻿using Newtonsoft.Json;
using System;
using System.ComponentModel;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;

namespace ProductTool.Tools
{
    public class ServiceHelper
    {
        /// <summary>
        /// 调用服务，默认post方式
        /// </summary>
        /// <typeparam name="T">返回的数据类型</typeparam>
        /// <param name="url">请求地址</param>
        /// <param name="token">用户token</param>
        /// <param name="param">参数</param>
        /// <returns></returns>
        public static T CallService<T>(string url, dynamic param = null, string token = null, Method method = Method.Post) where T : new()
        {
            T result = new T();
            string responseString=string.Empty;

            try
            {
                using (var client = new HttpClient { Timeout = new TimeSpan(0, 0, 60) })
                {
                    if (method == Method.Post)
                    {
                        param = param ?? (new { });
                        string jsonString = JsonConvert.SerializeObject(param);
                        byte[] bytes = Encoding.UTF8.GetBytes(jsonString);
                        using (StreamContent sc = new StreamContent(new MemoryStream(bytes)))
                        {
                            sc.Headers.ContentLength = bytes.Length;
                            sc.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                            sc.Headers.Add("token", token);
                            HttpResponseMessage response = client.PostAsync(new Uri(url), sc).Result;
                            responseString = response.Content.ReadAsStringAsync().Result;
                        }
                    }
                    else
                    {
                        client.DefaultRequestHeaders.Add("token", token);
                        responseString = client.GetStringAsync(new Uri(url)).Result;
                    }
                }
                result = JsonConvert.DeserializeObject<T>(responseString);
            }
            catch (Exception ex)
            {
                Console.WriteLine("call service error:"+ex.Message+":"+ responseString);
                return default(T);
            }
            return result;
        }

        /// <summary>
        /// get方式访问服务
        /// </summary>
        /// <typeparam name="T">返回数据类型</typeparam>
        /// <param name="url">请求地址</param>
        /// <param name="token">用户token</param>
        /// <returns></returns>
        public static T CallServiceForGet<T>(string url, string token = null) where T : new()
        {
            T result = new T();
            string responseString;
            using (var client = new HttpClient { Timeout=new TimeSpan(0,0,60) })
            {
                client.DefaultRequestHeaders.Add("token", token);
                responseString = client.GetStringAsync(new Uri(url)).Result;
            }
            result = JsonConvert.DeserializeObject<T>(responseString);
            return result;
        }

        /// <summary>
        /// get方式访问服务
        /// </summary>
        /// <typeparam name="T">返回数据类型</typeparam>
        /// <param name="url">请求地址</param>
        /// <returns></returns>
        public static string CallServiceForGet(string url, string token = null)
        {
            string responseString = null;
            try
            {
                using (var client = new HttpClient { Timeout = new TimeSpan(0, 0, 60) })
                {
                    client.DefaultRequestHeaders.Add("token", token);
                    responseString = client.GetStringAsync(new Uri(url)).Result;
                }
            }
            catch (Exception)
            {
                return responseString;
            }
            return responseString;
        }
    }

    public enum Method
    {
        /// <summary>
        /// get 方式
        /// </summary>
        [Description("get方式")]
        Get,
        /// <summary>
        /// post 方式
        /// </summary>
        [Description("post方式")]
        Post
    }

}
